import { Button, Dialog, Form, TextArea, Toast } from 'antd-mobile'
import PageComponent from '@components/pageComponent'
import MultiSelector from '@components/multiSelector'
import { useEffect, useMemo, useState } from 'react'
import { getCaseDetailRequest, createDefince } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import PageLoading from '@components/pageLoading'
import PageEmpty from '@components/pageEmpty'
import { getPartyListByAccountId } from './util'
import { useAppDispatch, useAppSelector } from '@src/redux/hook'
import FilePicker from '@components/filePicker'
import { setProgress, setProgressVisible } from '@src/redux/reducers/common'
import { requestFiles } from '@src/assets/js/request'
import { pop } from '@src/redux/reducers/pages'
import { refreshCaseEditVersion } from '@src/redux/reducers/cases'

const { Item, useForm } = Form

async function initCaseDetail (caseid, setLoading, setData) {
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseDetailRequest(caseid))
  setLoading(false)
  if (e === null && d !== null) {
    setData(d)
  }
}

// 格式化数据
function formatData (d, c, type, userList, fileid) {
  const userMap = new Map()
  userList.forEach(li => {
    userMap.set(li.id, li.name)
  })
  const defender = d.defenderid.map(id => {
    return userMap.get(id)
  })
  return {
    caseid: c.id,
    defender: defender.join(),
    defenderid: d.defenderid.join(),
    statement: d.statement,
    fileid,
    submittal_type: type,
    claimid: c.claim.id
  }
}

async function submitHandle (d, caseDetail, type, userList, dispatch) {
  let fileid = ''
  if (d.file && d.file.length > 0) {
    dispatch(setProgressVisible(true))
    const [e, r] = await awaitWrap(requestFiles(d.file, v => { dispatch(setProgress(v)) }))
    dispatch(setProgressVisible(false))
    if (e !== null) {
      return undefined
    }
    if (e === null && r !== null) {
      fileid = r.map(li => li.id).join(',')
    }
  }
  delete d.file
  delete d.defender
  Toast.show({ content: '提交中', duration: 0, icon: 'loading' })
  const data = formatData(d, caseDetail, type, userList, fileid)
  const [e] = await awaitWrap(createDefince(data))
  if (e === null) {
    Toast.clear()
    Toast.show({ content: '提交成功', icon: 'success' })
    dispatch(pop())
    dispatch(refreshCaseEditVersion())
  }
}

function Main ({ meta }) {
  const [formRef] = useForm()
  const dispatch = useAppDispatch()
  const userInfo = useAppSelector(state => state.basic.userInfo)
  const [caseDetail, setCaseDetail] = useState(null)
  const [loading, setLoading] = useState(true)
  const [type, setType] = useState('')
  const [userList, setUserList] = useState([])
  const caseid = useMemo(() => {
    return meta && meta.caseid ? meta.caseid : ''
  }, [meta])
  const names = useMemo(() => {
    return userList.map(li => li.name)
  }, [userList])
  useEffect(() => {
    if (caseid) {
      initCaseDetail(caseid, setLoading, setCaseDetail)
    }
  }, [caseid])
  useEffect(() => {
    if (caseDetail && userInfo) {
      const o = getPartyListByAccountId(caseDetail, userInfo.id)
      setUserList(o.list)
      setType(o.type)
    }
  }, [caseDetail, userInfo])
  if (loading) {
    return (
      <PageComponent title='添加答辩'>
        <PageLoading />
      </PageComponent>
    )
  }
  if (!caseDetail) {
    return (
      <PageComponent title='添加答辩'>
        <PageEmpty />
      </PageComponent>
    )
  }
  return (
    <PageComponent title='添加答辩'>
      <Form form={formRef} layout='horizontal' onFinish={d => {
        Dialog.confirm({
          title: '您确定要提交吗？',
          onConfirm: () => {
            submitHandle(d, caseDetail, type, userList, dispatch)
          }
        })
      }}>
        <Item noStyle name='defenderid'><span /></Item>
        <MultiSelector label='答辩人' name='defender' rules={[{ required: true, message: '答辩人不能为空' }]} options={names} onChange={v => {
          const ids = userList.filter(li => v.includes(li.name)).map(li => li.id)
          formRef.setFieldValue('defenderid', ids)
        }} />
        <Item label='答辩内容' name='statement' rules={[{ required: true, message: '答辩内容不能为空' }]}>
          <TextArea placeholder='请输入' clearable />
        </Item>
        <Item name='file' label='附件'>
          <FilePicker />
        </Item>
        <Item>
          <Button type='submit' block color='primary'>提交</Button>
        </Item>
      </Form>
    </PageComponent>
  )
}

export default Main
